#region Copyright (c) 2006-2009 Widgetsphere LLC, All Rights Reserved
//--------------------------------------------------------------------- *
//                          Widgetsphere  LLC                           *
//             Copyright (c) 2006-2009 All Rights reserved              *
//                                                                      *
//                                                                      *
//This file and its contents are protected by United States and         *
//International copyright laws.  Unauthorized reproduction and/or       *
//distribution of all or any portion of the code contained herein       *
//is strictly prohibited and will result in severe civil and criminal   *
//penalties.  Any violations of this copyright will be prosecuted       *
//to the fullest extent possible under law.                             *
//                                                                      *
//THE SOURCE CODE CONTAINED HEREIN AND IN RELATED FILES IS PROVIDED     *
//TO THE REGISTERED DEVELOPER FOR THE PURPOSES OF EDUCATION AND         *
//TROUBLESHOOTING. UNDER NO CIRCUMSTANCES MAY ANY PORTION OF THE SOURCE *
//CODE BE DISTRIBUTED, DISCLOSED OR OTHERWISE MADE AVAILABLE TO ANY     *
//THIRD PARTY WITHOUT THE EXPRESS WRITTEN CONSENT OF WIDGETSPHERE LLC   *
//                                                                      *
//UNDER NO CIRCUMSTANCES MAY THE SOURCE CODE BE USED IN WHOLE OR IN     *
//PART, AS THE BASIS FOR CREATING A PRODUCT THAT PROVIDES THE SAME, OR  *
//SUBSTANTIALLY THE SAME, FUNCTIONALITY AS ANY WIDGETSPHERE PRODUCT.    *
//                                                                      *
//THE REGISTERED DEVELOPER ACKNOWLEDGES THAT THIS SOURCE CODE           *
//CONTAINS VALUABLE AND PROPRIETARY TRADE SECRETS OF WIDGETSPHERE,      *
//INC.  THE REGISTERED DEVELOPER AGREES TO EXPEND EVERY EFFORT TO       *
//INSURE ITS CONFIDENTIALITY.                                           *
//                                                                      *
//THE END USER LICENSE AGREEMENT (EULA) ACCOMPANYING THE PRODUCT        *
//PERMITS THE REGISTERED DEVELOPER TO REDISTRIBUTE THE PRODUCT IN       *
//EXECUTABLE FORM ONLY IN SUPPORT OF APPLICATIONS WRITTEN USING         *
//THE PRODUCT.  IT DOES NOT PROVIDE ANY RIGHTS REGARDING THE            *
//SOURCE CODE CONTAINED HEREIN.                                         *
//                                                                      *
//THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE.              *
//--------------------------------------------------------------------- *
#endregion
using System;
using System.Xml;
using Widgetsphere.Generator.Models;
using Widgetsphere.Generator.Common.GeneratorFramework;
using Widgetsphere.Generator.ProjectItemGenerators;
using System.Collections;
using System.Windows.Forms;
using EnvDTE;
using Widgetsphere.Generator.Common.Util;
namespace Widgetsphere.Generator
{
	[GeneratorAttribute("{4B5CFCAF-C668-4d40-947C-83B2AAEBB2B5}", "Widgetsphere Model", typeof(Widgetsphere.Generator.Forms.ModelPropertiesControl))]
	public class WidgetsphereGeneratorProject : IGenerator, IXMLable
	{
		#region Member Variables

		private IModelObjectController _rootController;
		private string _fileName = "";

		#endregion

		#region Constructors

		public WidgetsphereGeneratorProject()
		{
			ModelRoot root = new ModelRoot(null);
			root.GeneratorProject = this;
			_rootController = new ModelRootController(root);
		}

		#endregion

		#region Events

		public event Widgetsphere.Generator.Common.GeneratorFramework.VerifyDelegate VerifyComplete;
		protected void OnVerifyComplete(object sender, Widgetsphere.Generator.Common.EventArgs.MessageCollectionEventArgs e)
		{
			if (this.VerifyComplete != null)
				this.VerifyComplete(sender, e);
		}

		#endregion

		#region IXMLable Members

		public void XmlAppend(XmlNode node)
		{
			XmlDocument oDoc = node.OwnerDocument;
			XmlNode ModelRootNode = oDoc.CreateElement("ModelRoot");
			RootController.Object.XmlAppend(ModelRootNode);
			node.AppendChild(ModelRootNode);
		}

		public void XmlLoad(XmlNode node)
		{
			XmlNode ModelRootNode = node.SelectSingleNode("ModelRoot");
			RootController.Object.XmlLoad(ModelRootNode);
			((ModelRoot)RootController.Object).CleanUp();
		}

		#endregion

		#region DomainProjectName

		public static string DomainProjectName(ModelRoot model)
		{
			string projectName = model.CompanyName;
			if (model.ProjectName != string.Empty)
				projectName += "." + model.ProjectName;
			return projectName;
		}

		public static string WinUIProjectName(ModelRoot model)
		{
			return string.Format("{0}.{1}.WinUI", model.CompanyName, model.ProjectName);
		}

		#endregion

		#region IGeneratorProject

		public IModelObjectController RootController
		{
			get { return _rootController; }
		}

		public ImageList ImageList
		{
			get { return ImageHelper.GetImageList(); }
		}

		public MenuCommand[] GetMenuCommands()
		{
			MenuCommand menuVerify = new DefaultMenuCommand();
			menuVerify.Text = "Verify";
			menuVerify.Click += new EventHandler(menuVerify_Click);

			MenuCommand menu1 = new DefaultMenuCommand();
			menu1.Text = "-";

			MenuCommand menuImport = new DefaultMenuCommand();
			menuImport.Text = "Import Database";
			menuImport.Click += new EventHandler(menuImport_Click);

			return new MenuCommand[] { menuVerify, menu1, menuImport };
		}

		#endregion

		#region Menu Handlers

		private void menuImport_Click(object sender, System.EventArgs e)
		{
			ConnectStringForm F = new ConnectStringForm();
			if (F.ShowDialog() != DialogResult.OK)
				return;

			if (true)
			{
				//Non-Threaded
				SqlSchemaToModel sstm = new SqlSchemaToModel(F.ConnectString);
				sstm.GetProjectFromSqlSchema(this);				
				//this.RootController.Node.RefreshDeep();
			}
			else
			{
				//Theaded
				DatabaseImportThreader dit = new DatabaseImportThreader(this, F.ConnectString);
				System.Threading.ThreadStart ts = new System.Threading.ThreadStart(dit.Run);
				System.Threading.Thread newThread = new System.Threading.Thread(ts);
				newThread.Start();
				while (newThread.ThreadState != System.Threading.ThreadState.Stopped)
				{
					Application.DoEvents();
				}
			}

		}

		private void menuVerify_Click(object sender, System.EventArgs e)
		{
			MessageCollection list = ((BaseModelObjectController)_rootController).Verify();
			this.OnVerifyComplete(this, new Widgetsphere.Generator.Common.EventArgs.MessageCollectionEventArgs(list));
		}

		#endregion

		#region IGenerator Members

		public string FileName
		{
			get { return _fileName; }
			set { _fileName = value; }
		}

		public void HandleCommand(string command)
		{
			if (command == "ImportModel")
			{
				ConnectStringForm F = new ConnectStringForm();
				if (F.ShowDialog() != DialogResult.OK)
					return;

				SqlSchemaToModel sstm = new SqlSchemaToModel(F.ConnectString);
				//sstm.GetProjectFromSqlSchema(this);

				//Try something new (2/7/2009)
				Widgetsphere.Generator.SqlSchemaToModel.ImportReturnConstants retval = sstm.ImportModel(this);

				switch (retval)
				{
					case SqlSchemaToModel.ImportReturnConstants.Aborted:
						MessageBox.Show("The import was aborted.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
						break;
					case SqlSchemaToModel.ImportReturnConstants.NoChange:
						MessageBox.Show("This model is up-to-date. There are no changes to refresh.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
						break;
					case SqlSchemaToModel.ImportReturnConstants.Success:
						MessageBox.Show("The import was completed successfully.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
						break;
				}

			}
		}

		#endregion
	}

	#region DatabaseImportThreader

	internal class DatabaseImportThreader
	{
		private WidgetsphereGeneratorProject _parent = null;
		private string _connectionString = "";
		internal DatabaseImportThreader(WidgetsphereGeneratorProject parent, string connectionString)
		{
			_parent = parent;
			_connectionString = connectionString;
		}

		internal void Run()
		{
			SqlSchemaToModel sstm = new SqlSchemaToModel(_connectionString);
			sstm.GetProjectFromSqlSchema(_parent);
			_parent.RootController.Node.RefreshDeep();
		}

	}

	#endregion

}
